package task

import (
	"fmt"
	"gitee.com/rainbowserver_go/config"
	"github.com/Unknwon/goconfig"
	"github.com/labstack/gommon/log"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"sort"
	"strconv"
	"strings"
	"unsafe"
)

type CarGameTask struct {
	mongodb     *mgo.Session
	db          *mgo.Database
	carBetTable *mgo.Collection
}

type BetRanking struct {
	Ranking int8
	User    string
	Bets    int
}

type CarBet struct {
	Id       int64
	Gameid   int64
	Userid   int64
	User     string
	Digital  int8
	Quantity string
	Reward   string
	Bettime  int32
}

func (task *CarGameTask) Init() {
	cfg, _ := goconfig.LoadConfigFile(config.CONFIG_FILE_NAME)
	mongocfg, _ := cfg.GetSection("mongodb")
	url := "mongodb://" + mongocfg["user"] + ":" + mongocfg["pass"] + "@" + mongocfg["host"] + ":" + mongocfg["port"] + "/" + mongocfg["db"]
	mongodb, err := mgo.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	//defer mongodb.Close()
	mongodb.SetMode(mgo.Monotonic, true)
	task.mongodb = mongodb
	task.db = mongodb.DB(mongocfg["db"])
	task.carBetTable = task.db.C("carbet")
}

func (task *CarGameTask) Start() {
	result := []CarBet{}
	iter := task.carBetTable.Find(bson.M{}).Limit(0).Sort("-bettime").Iter()
	err := iter.All(&result)

	if err == nil {
		rank := make(map[int64]BetRanking)
		sortMap := make(map[int]int)

		var maxUserid = 0
		//重新组合信息
		for i := 0; i < len(result); i++ {
			ranking := BetRanking{}
			ranking.User = result[i].User

			bets, err := strconv.ParseFloat(strings.Replace(result[i].Quantity, " EOS", "", 1), 32)

			if err == nil {
				ranking.Bets = rank[result[i].Userid].Bets + (int)(bets*10000)
				rank[result[i].Userid] = ranking
				idPointer := (*int)(unsafe.Pointer(&result[i].Userid))
				idd16 := *idPointer
				if idd16 > maxUserid {
					maxUserid = idd16
				}
				sortMap[idd16] = ranking.Bets
			}
		}

		var keys []int

		for x := 1; x <= maxUserid+1; x++ {
			if sortMap[x+1] != 0 {
				keys = append(keys, sortMap[x+1])
			} else {
				keys = append(keys, 0)
			}
		}

		sort.Ints(keys)

		for k, _ := range keys {
			fmt.Println("Key:", k, "Value:", sortMap[k])
		}

		print("ttt")
	}
}
